const jwt = require('jsonwebtoken');
const SECRET = 'milk_tea_secret';

function verifyToken(req, res, next) {
  const authHeader = req.headers.authorization;
  if (!authHeader) return res.json({ code: 401, message: '未登录' });

  // 支持 'Bearer <token>' 与直接 '<token>'
  const token = authHeader.includes(' ') ? authHeader.split(' ')[1] : authHeader;
  if (!token) return res.json({ code: 401, message: '未登录' });

  jwt.verify(token, SECRET, (err, user) => {
    if (err) return res.json({ code: 403, message: 'token无效' });
    req.user = user;
    next();
  });
}

module.exports = { verifyToken, SECRET };